package cn.king.basic.controller;

import cn.king.basic.util.AjaxResult;
import cn.king.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 *  上传
 *  下载 = 不需要
 *  查看 = 路径
 *  删除
 *  更新 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){ //参数名必须为file，因为前端默认的就是file
        try {
            //调用工具类
            String name = file.getOriginalFilename(); //xxx.jpg
            String extName = name.substring(name.lastIndexOf(".") + 1); //jpg，+1才会没有前面那个.
            //调用方法
            String fileName = FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setObj(fileName);
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 文件删除
     * delete http://Localhost:8080/fastDfs/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     * 后端接收: @Pathv("/{a}/tb}/tcJ/tdI")，太麻烦，所以不用
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8C/CaAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     */
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam("path")String path){
        try {
            //path = /group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            path = path.substring(1); // group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            String groupName = path.substring(0,path.indexOf("/")); // group1
            String fileName = path.substring(path.indexOf("/")+1); // M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            //调用FastDfsUtils工具类删除方法
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
}
